﻿#include "BackgroundImageDialog.h"
#include "ui_BackgroundImageDialog.h"
#include "stores/DataStroes.h"
#include "components/Toast/Toast.h"

#include <QFileDialog>
#include <QTimer>


BackgroundImageDialog::BackgroundImageDialog(QWidget *parent)
    : FDialog(parent)
    , ui(new Ui::BackgroundImageDialog)
{
    ui->setupUi(this);
    setWindowTitle(tr("Background Image"));

    m_imgPath = DataStroes::instance()->settings()->model().data().general.background_imgae;

    QTimer::singleShot(100, this, &BackgroundImageDialog::initView);
}

BackgroundImageDialog::~BackgroundImageDialog()
{
    delete ui;
}

void BackgroundImageDialog::initView()
{
    if (m_imgPath.isEmpty()) {  // 空值显示默认图片
        ui->imageView->setImage(QImage(StoreFilePath::defaultBackgroundImagePath()));
    } else if (m_imgPath == "$") {  // $ 值不显示图片
        ui->imageView->clear();
    } else {
        ui->leImgPath->setText(m_imgPath);
        ui->imageView->setImage(QImage(m_imgPath));
    }
}

void BackgroundImageDialog::on_btnBrowse_clicked()
{
    QString path = QFileDialog::getOpenFileName(this, tr("Select Background Image"), "", tr("Image Files (*.png *.jpg *.bmp *.jpeg *.webp)"));
    if (path.isEmpty()) {
        return;
    }
    ui->leImgPath->setText(path);
    m_imgPath = path;
    initView();
}


void BackgroundImageDialog::on_btnPreview_clicked()
{
    ui->imageView->clear();
    if (m_imgPath.isEmpty()) {  // 空值显示默认图片
        setBackgroundImage(StoreFilePath::defaultBackgroundImagePath());
    } else {
        setBackgroundImage(m_imgPath);
    }
}


void BackgroundImageDialog::on_btnApply_clicked()
{
    if (m_imgPath == "$") Toast::info(tr("Clearing the background will take effect after the app restarts"));
    DataStroes::instance()->settings()->model().data().general.background_imgae = m_imgPath;
    DataStroes::instance()->settings()->save();
    setGlobalBackgroundImage(m_imgPath);
    accept();
}


void BackgroundImageDialog::on_btnCancel_clicked()
{
    reject();
}


void BackgroundImageDialog::on_btnReset_clicked()
{
    m_imgPath = "";
    ui->leImgPath->clear();
    initView();
}


void BackgroundImageDialog::on_btnClear_clicked()
{
    m_imgPath = "$";
    ui->leImgPath->clear();
    initView();
}

